﻿using System.ServiceModel;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using SpectrumAnalyser.Data.Common.Contracts;
using SpectrumAnalyser.Services.Common.Extensions;
using SpectrumAnalyser.Services.ExpertiseResultStorageServiceContracts;

namespace SpectrumAnalyser.Services.Common.CallHandlers
{
    public class RequireRepositoryFactoryCallHandler:ICallHandler
    {
        private readonly IUnityContainer _unityContainer;

        public RequireRepositoryFactoryCallHandler(IUnityContainer unityContainer)
        {
            _unityContainer = unityContainer;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (input.Target is IWithRepositoryFactory)
            {
                var instanceNameHeader = OperationContext.Current.GetInstanceNameHeader();

                (input.Target as IWithRepositoryFactory).RepositoryFactory =
                    _unityContainer.Resolve<IRepositoryFactory>(new ParameterOverride("instanceContext",
                                                                                      _unityContainer
                                                                                          .Resolve
                                                                                          <
                                                                                          SpectrumAnalyser.Common.
                                                                                          InstanceContext.
                                                                                          InstanceContext>(
                                                                                              instanceNameHeader
                                                                                                  .InstanceName)));
            }
            return getNext()(input, getNext);
        }

        public int Order { get; set; }
    }
}